<!-- 角色管理 -->
<template>
  <div class="role-index">
    <div class="role-sear" v-if="isShowSear">
      <el-form size="mini" inline>
        <el-form-item label="关键字">
          <el-input
            placeholder="关键字检索(名称/授权标识)"
            v-model="searParams.keyword"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色类型">
          <el-select
            v-model="searParams.abilityCode"
            size="mini"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in typeList"
              :key="item.code"
              :label="item.remark"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建人">
          <el-select
            v-model="searParams.createBy"
            size="mini"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in createTenantList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createDate"
            style="width: 300px"
            size="mini"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="center"
            @change="handleSelectDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-button size="mini" type="primary" @click="handleSear"
          >查询</el-button
        >
        <el-button size="mini" @click="resetSearParams()">重置</el-button>
      </el-form>
    </div>
    <div class="role-oper">
      <div class="role-oper-left">
        <el-button
          type="primary"
          size="mini"
          plain
          icon="el-icon-plus"
          @click="handlePreAdd"
          >新增</el-button
        >
        <el-button
          type="success"
          size="mini"
          plain
          icon="el-icon-edit"
          @click="handleModifyBatch"
          >修改</el-button
        >
        <el-button
          type="danger"
          size="mini"
          plain
          icon="el-icon-delete"
          @click="handleRemoveBatch()"
        >
          删除</el-button
        >
        <el-button size="mini" plain icon="el-icon-sort" @click="handleExband"
          >展开/折叠</el-button
        >
      </div>
      <div class="role-oper-right">
        <el-button
          icon="el-icon-search"
          size="mini"
          circle
          @click="isShowSear = !isShowSear"
        ></el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          circle
          @click="list()"
        ></el-button>
      </div>
    </div>
    <div class="role-list">
      <el-table
        stripe
        highlight-current-row
        v-if="isRefreshTable"
        :data="rolePage.list"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        :default-expand-all="isExpand"
        tooltip-effect="dark"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionModify"
        @row-click="rowClick"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column prop="id" label="ID" sortable width="180">
      </el-table-column> -->
        <el-table-column prop="name" label="角色名称" sortable width="150">
        </el-table-column>
        <el-table-column prop="auth" label="授权标识" width="150" align="left">
        </el-table-column>
        <el-table-column
          prop="createTenant"
          label="创建人"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createTenant.username }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.roleType != null ? scope.row.roleType.remark : "~" }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="150" align="center">
          <template slot-scope="scope">
            <el-input-number
              @change="handleModifyLevel(scope.row)"
              size="mini"
              v-model="scope.row.level"
              :min="1"
              :max="10"
            >
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="level"
          label="是否启用"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleModifyEnable(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="150">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >详情</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleModifySingle(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleRemoveSingle(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="page"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="rolePage.totalCount"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="rolePage.pageSize"
        @current-change="handleModifyOffset"
        @size-change="handleModifyLimit"
      >
      </el-pagination>
    </div>

    <add-comp
      :parents="roleList"
      :types="typeList"
      :enables="enableList"
      :apiPerms="apiPermList"
      :dataPerms="dataPermList"
      :entities="entityTypeList"
      @close="handleCloseAdd"
      @submit="handleSubmitAdd"
      @queryEntityType="getEntityType"
      @queryEntity="getEntity"
      v-if="isShowAdd"
    />
    <edit-comp
      :parents="roleList"
      :data="singleData"
      :types="typeList"
      :enables="enableList"
      :apiPerms="apiPermList"
      :dataPerms="dataPermList"
      @close="handleCloseEdit"
      @submit="handleSubmitEdit"
      v-if="isShowEdit"
    />
  </div>
</template>

<script>
import { isNotEmpty, isEmpty, isNotNull, isNull } from "@/utils/validate";
import { emit } from "process";
import AddComp from "./AddComp.vue";
import EditComp from "./EditComp.vue";
export default {
  name: "",
  components: {},
  data() {
    return {
      isRefreshTable: true,
      isExpand: false,
      isShowSear: true,
      isShowAdd: false,
      isShowEdit: false,
      searParams: {},
      rolePage: [],
      selectItems: [],
      selectIds: [],
      createTenantList: [],
      typeList: [],
      createDate: "",
      roleList: [],
      singleData: {},
      enableList: [],
      apiPermList: [],
      dataPermList: [],
      entityTypeList: [],
    };
  },
  created() {
    this.getCreateTenantList();
    this.getTypes();
    this.resetSearParams();
    this.list();
  },
  components: {
    AddComp,
    EditComp,
  },
  mounted() {},
  methods: {
    /**
     * 重置搜索参数
     */
    resetSearParams() {
      this.createDate = [];
      this.searParams = {
        offset: 1,
        limit: 5,
        createBy: "",
        fromTime: "",
        toTime: "",
        keyword: "",
      };
    },
    /**
     * 选中时间
     */
    handleSelectDate(val) {
      this.searParams.fromTime = val[0];
      this.searParams.toTime = val[1];
    },
    /**
     * 查询角色列表
     */
    list() {
      this.$store.dispatch("role/list", this.searParams).then((res) => {
        if (res.code === 0) {
          this.rolePage = res.data;
        }
      });
    },
    /**
     * 获取创建人列表
     */
    getCreateTenantList() {
      this.$store.dispatch("role/getCreateTenant").then((res) => {
        if (res.code === 0) {
          this.createTenantList = res.data;
        }
      });
    },
    /**
     * 查询角色类型列表
     */
    getTypes() {
      this.$store.dispatch("role/getTypes").then((res) => {
        if (res.code === 0) {
          this.typeList = res.data;
        }
      });
    },
    /**
     * 页码改变
     */
    handleModifyOffset(offset) {
      this.searParams.offset = offset;
      this.list();
    },
    /**
     * 页数改变
     */
    handleModifyLimit(limit) {
      this.searParams.limit = limit;
      this.list();
    },
    /**
     * 执行搜索
     */
    handleSear() {
      this.list();
    },
    /**
     * 展开/折叠
     */
    handleExband() {
      this.isRefreshTable = false;
      this.isExpand = !this.isExpand;
      this.$nextTick(() => {
        this.isRefreshTable = true;
      });
    },
    /**
     * 选中状态改变
     */
    handleSelectionModify(roleItem) {
      this.selectItems = [];
      this.selectIds = [];
      for (let i = 0; i < roleItem.length; i++) {
        this.selectItems.push(roleItem[i]);
        this.selectIds.push(roleItem[i].id);
      }
    },
    /**
     * 批删
     */
    handleRemoveBatch() {
      this.doRemove(this.selectIds);
    },
    /**
     * 单删
     */
    handleRemoveSingle(roleItem) {
      this.doRemove([roleItem.id]);
    },
    /**
     * 执行删除操作
     */
    doRemove(roleIds) {
      if (isEmpty(roleIds)) {
        this.$message("未选中角色");
        return;
      }
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("role/removeByIds", roleIds).then((res) => {
            if (res.code === 0) {
              this.list();
              this.$message({
                message: "删除角色成功",
                type: "success",
              });
            } else {
              this.$message.error("删除角色失败");
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 获取权限实体类型
     */
    getEntityType() {
      this.$store.dispatch("authEntity/getEntityTypes").then((res) => {
        if (res.code === 0) {
          this.entityTypeList = res.data;
          this.$emit("getEntityTypeList", this.entityTypeList);
        }
      });
    },
    /**
     * 通过类型编码获取权限实体
     */
    getEntity(typeCode) {
      console.log("bbb");
      this.$store.dispatch("authEntity/getByTypeCode", typeCode).then((res) => {
        if (res.code === 0) {
          this.dataPermList = res.data;
          this.$emit("getDataPermList", this.dataPermList);
        }
      });
    },
    /**
     * 通过类型编码获取权限实体id
     */
    getEntityIdsByTypeCode(typeCode) {
      this.$store
        .dispatch("authEntity/getEntityIdsByTypeCode", typeCode)
        .then((res) => {
          console.log(res);
        });
    },
    /**
     * 查询禁用启用状态列表
     */
    getEnable() {
      this.$store.dispatch("role/getEnable").then((res) => {
        if (res.code === 0) {
          this.enableList = res.data;
        }
      });
    },
    /**
     * 查询当前租户权限列表菜单
     */
    getPermListInAuth() {
      this.$store.dispatch("menu/getPermListInAuth").then((res) => {
        if (res.code === 0) {
          this.apiPermList = res.data;
          this.$emit("getApiPermList", this.apiPermList);
        }
      });
    },
    /**
     * 预添加
     */
    handlePreAdd() {
      this.getInAuth();
      this.getEnable();
      this.getPermListInAuth();
      this.isShowAdd = true;
    },
    /**
     * 提交创建
     */
    handleSubmitAdd(roleForm) {
      this.$store.dispatch("role/create", roleForm).then((res) => {
        if (res.code === 0) {
          this.isShowAdd = false;
          this.list();
          this.$message({
            message: "创建角色成功",
            type: "success",
          });
        } else {
          this.$message.error("创建角色失败");
        }
      });
    },
    /**
     * 关闭创建对话框
     */
    handleCloseAdd() {
      this.isShowAdd = false;
    },
    /**
     * 获取角色列表
     */
    getInAuth() {
      this.$store.dispatch("role/getInAuth").then((res) => {
        if (res.code === 0) {
          this.roleList = res.data;
        }
      });
    },
    /**
     * 修改启用状态
     */
    handleModifyEnable(val) {
      const roleForm = {
        id: val.id,
        enable: val.enable,
      };
      this.doModify(roleForm);
    },
    /**
     * 修改等级
     */
    handleModifyLevel(val) {
      const roleForm = {
        id: val.id,
        level: val.level,
      };
      this.doModify(roleForm);
    },
    /**
     * 单个修改
     */
    handleModifySingle(roleForm) {
      this.handlePreModify([roleForm]);
    },
    /**
     * 选中修改
     */
    handleModifyBatch() {
      this.handlePreModify(this.selectItems);
    },
    /**
     * 关闭编辑对话框
     */
    handleCloseEdit() {
      this.isShowEdit = false;
    },
    /**
     * 预修改操作
     */
    handlePreModify(roleForms) {
      if (roleForms == null || roleForms.length != 1) {
        this.$message({
          message: "请选择一个角色",
          type: "warning",
        });
        return;
      }
      const roleForm = roleForms[0];
      this.$store.dispatch("role/getById", roleForm.id).then((res) => {
        if (res.code === 0) {
          this.getEnable();
          this.getPermListInAuth();
          this.singleData = res.data;
          this.isShowEdit = true;
        } else {
          this.$message.error("同步角色数据失败");
        }
      });
    },
    /**
     * 提交修改
     */
    handleSubmitEdit(roleForm) {
      this.doModify(roleForm);
    },
    /**
     * 执行修改操作
     */
    doModify(roleForm) {
      this.$store.dispatch("role/modifyById", roleForm).then((res) => {
        if (res.code === 0) {
          this.isShowEdit = false;
          this.list();
          this.$message({
            message: "修改角色成功",
            type: "success",
          });
        } else {
          this.$message.error("修改角色失败");
        }
      });
    },
    rowClick(row, column, event) {
      console.log({ row, column, event });
      this.$emit("roleRowClick", row.id);
    },
  },
};
</script>

<style scoped>
.role-index {
  height: auto;
  margin: 1%;
  margin-top: 0;
  display: flex;
  flex-direction: column;
}

.role-oper {
  margin: 12px 0 12px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.role-list {
  text-align: center;
}
</style>
